<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能写作助手 - 内网部署</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 32px;
            margin-bottom: 10px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 16px;
        }
        
        .status-bar {
            background: #f8f9fa;
            padding: 15px 30px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 14px;
        }
        
        .status-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #28a745;
        }
        
        .status-dot.offline {
            background: #dc3545;
        }
        
        .tabs {
            display: flex;
            background: #f8f9fa;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .tab {
            padding: 15px 25px;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: all 0.3s;
            font-weight: 500;
        }
        
        .tab.active {
            border-bottom-color: #667eea;
            color: #667eea;
            background: white;
        }
        
        .tab:hover {
            background: #e9ecef;
        }
        
        .tab-content {
            display: none;
            padding: 30px;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }
        
        .form-control {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        textarea.form-control {
            min-height: 120px;
            resize: vertical;
        }
        
        .select-control {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
            background: white;
        }
        
        .btn {
            padding: 12px 24px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background 0.3s;
        }
        
        .btn:hover {
            background: #5a6fd8;
        }
        
        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .btn-secondary {
            background: #6c757d;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .result-container {
            margin-top: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }
        
        .result-title {
            font-weight: 600;
            margin-bottom: 10px;
            color: #333;
        }
        
        .result-content {
            white-space: pre-wrap;
            line-height: 1.6;
        }
        
        .thinking {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin: 10px 0;
            border-radius: 4px;
            font-style: italic;
        }
        
        .error {
            background: #f8d7da;
            border-left: 4px solid #dc3545;
            padding: 15px;
            margin: 10px 0;
            border-radius: 4px;
            color: #721c24;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #667eea;
        }
        

        
        .api-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
            text-align: center;
        }
        
        /* 模态窗口样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            animation: modalSlideIn 0.3s ease;
        }
        
        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-header h3 {
            margin: 0;
            color: #333;
            font-size: 18px;
        }
        
        .close {
            color: #aaa;
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
        }
        
        .close:hover {
            color: #333;
        }
        
        .modal-body {
            padding: 24px;
        }
        
        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid #e0e0e0;
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }
        
        /* 进度条样式 */
        .progress-container {
            margin-top: 15px;
        }
        
        .progress-bar {
            width: 100%;
            height: 8px;
            background-color: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background-color: #667eea;
            border-radius: 4px;
            transition: width 0.3s ease;
            width: 0%;
        }
        
        .progress-text {
            text-align: center;
            margin-top: 8px;
            font-size: 12px;
            color: #666;
        }
        
        .success {
            background: #d4edda;
            border-left: 4px solid #28a745;
            padding: 12px;
            border-radius: 4px;
            color: #155724;
        }
        
        .stat-number {
            font-size: 24px;
            font-weight: 600;
            color: #667eea;
        }
        
        .stat-label {
            font-size: 14px;
            color: #666;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .fade-in {
            animation: fadeIn 0.3s ease-in;
        }
        
        /* 标题生成结果样式 */
        .title-result {
            background: white;
            border-radius: 8px;
            padding: 极速赛车开奖历史记录0px;
            border: 1px solid #e0e0e0;
        }
        
        .title-main {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin-bottom: 15px;
            line-height: 1.3;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        
        .title-reason {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            border-left: 4px solid #28a745;\极速赛车开奖历史记录             font-size: 14px;
            line-height: 1.6;
            color: #555;
        }
        
        .title-reason strong {
            color: #28a745;
            margin-right: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>AI智能写作助手</h1>
            <p>内网部署 - 支持文本生成、文案润色</p>
        </div>
        
        <div class="status-bar">
            <div class="status-item">
                <div class="status-dot" id="statusDot"></div>
                <span>服务状态: <span id="statusText">检查中...</span></span>
            </div>
            <div class="status-item">
                <span>模型: Qwen3-0.6B (原始)</span>
            </div>
            <div class="status-item">
                <span id="serverTime">--:--:--</span>
            </div>
            <div class="status-item">
                <button class="btn btn-secondary" onclick="refreshStatus()" style="padding: 6px 12px; font-size: 12px;">刷新状态</button>
                <button class="btn" onclick="showQuantizePanel()" style="padding: 6px 12px; font-size: 12px; margin-left: 8px;">量化模型</button>
            </div>
        </div>
        
        <div class="tabs">
            <div class="tab active" data-tab="chat">聊天对话</div>
            <div class="tab" data-tab="generate">文本生成</div>
            <div class="tab" data-tab="rewrite">文案润色</div>
            <div class="tab" data-tab="status">系统状态</div>
        </div>
        
        <!-- 聊天对话标签 -->
        <div class="tab-content active" id="chatTab">
            <div class="form-group">
                <label for="chatInput">输入你的问题：</label>
                <textarea 
                    id="chatInput" 
                    class="form-control" 
                    placeholder="请输入你想要询问的问题..."
                    maxlength="1000"
                ></textarea>
            </div>
            <button class="btn" onclick="sendChat()" id="chatBtn">发送</button>
            
            <div class="result-container" id="chatResult" style="display: none;">
                <div class="result-title">回答结果：</div>
                <div class="result-content" id="chatOutput"></div>
            </div>
        </div>
        
        <!-- 文本生成标签 -->
        <div class="tab-content" id="generateTab">
            <div class="form-group">
                <label for="generatePrompt">输入提示词：</label>
                <textarea 
                    id="generatePrompt" 
                    class="form-control" 
                    placeholder="例如：写一篇关于人工智能的文章..."
                    maxlength="2000"
                ></textarea>
            </div>
            
            <div class="form-group">
                <label for="maxTokens">生成长度：</label>
                <input 
                    type="number" 
                    id="maxTokens" 
                    class="form-control" 
                    value="2048" 
                    min="100" 
                    max="4096"
                >
            </div>
            
            <div class="form-group">
                <label for="temperature">创造性：</label>
                <input 
                    type="range" 
                    id="temperature" 
                    class="form-control" 
                    min="0" 
                    max="1" 
                    step="0.1" 
                    value="0.7"
                >
                <span id="tempValue">0.7</span>
            </div>
            
            <button class="btn" onclick="generateText()" id="generateBtn">生成文本</button>
            
            <div class="result-container" id="generateResult" style="display: none;">
                <div class="result-title">生成结果：</div>
                <div class="result-content" id="generateOutput"></div>
            </div>
        </div>
        
        <!-- 文案润色标签 -->
        <div class="tab-content" id="rewriteTab">
            <div class="form-group">
                <label for="rewriteText">需要润色的文本：</label>
                <textarea 
                    id="rewriteText" 
                    class="form-control" 
                    placeholder="请输入需要润色的文案..."
                    maxlength="1000"
                ></textarea>
            </div>
            
            <div class="form-group">
                <label for="rewriteStyle">润色风格：</label>
                <select id="rewriteStyle" class="select-control">
                    <option value="professional">专业商务</option>
                    <option value="creative">创意营销</option>
                    <option value="academic">学术论文</option>
                    <option value="casual">轻松口语</option>
                    <option value="formal">正式公文</option>
                </select>
            </div>
            
            <button class="btn" onclick="rewriteText()" id="rewriteBtn">润色文案</button>
            
            <div class="result-container" id="rewriteResult" style="display: none;">
                <div class="result-title">原始文本：</div>
                <div class="result-content" id="originalText"></div>
                
                <div class="result-title" style="margin-top: 20px;">润色结果：</div>
                <div class="result-content" id="rewrittenText"></div>
            </div>
        </div>


        

        
        <!-- 系统状态标签 -->
        <div class="tab-content" id="statusTab">
            <div class="result-title">API服务状态</div>
            
            <div class="api-stats" id="apiStats">
                <div class="stat-card">
                    <div class="stat-number" id="generateCount">0</div>
                    <div class="stat-label">文本生成次数</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="rewriteCount">0</div>
                    <div class="stat-label">文案润色次数</div>
                </div>

                <div class="stat-card">
                    <div class="stat-number" id="chatCount">0</div>
                    <div class="stat-label">聊天对话次数</div>
                </div>
            </div>
            
            <div class="result-title" style="margin-top: 30px;">最近使用时间</div>
            <div class="result-content">
                <div>文本生成: <span id="generateTime">从未使用</span></div>
                <div>文案润色: <span id="rewriteTime">从未使用</span></div>

                <div>聊天对话: <span id="chatTime">从未使用</span></div>
            </div>
            
            <button class="btn" onclick="refreshStatus()" style="margin-top: 20px;">刷新状态</button>
        </div>
    </div>

    <script>
        // 标签切换功能
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', () => {
                // 移除所有激活状态
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                
                // 添加当前激活状态
                tab.classList.add('active');
                const tabId = tab.getAttribute('data-tab');
                document.getElementById(tabId + 'Tab').classList.add('active');
                
                // 如果是状态标签，刷新状态
                if (tabId === 'status') {
                    refreshStatus();
                }
            });
        });
        
        // 温度滑块显示
        const tempSlider = document.getElementById('temperature');
        const tempValue = document.getElementById('tempValue');
        tempSlider.addEventListener('input', () => {
            tempValue.textContent = tempSlider.value;
        });
        
        // 服务器时间更新
        function updateServerTime() {
            const now = new Date();
            document.getElementById('serverTime').textContent = 
                now.toLocaleTimeString('zh-CN');
        }
        setInterval(updateServerTime, 1000);
        updateServerTime();
        
        // API调用函数
        async function callApi(endpoint, data) {
            const btn = document.getElementById(endpoint + 'Btn');
            const originalText = btn.textContent;
            
            btn.disabled = true;
            btn.textContent = '处理中...';
            
            try {
                const response = await fetch('/api/' + endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });
                
                return await response.json();
            } catch (error) {
                throw new Error('网络请求失败: ' + error.message);
            } finally {
                btn.disabled = false;
                btn.textContent = originalText;
            }
        }
        
        // 聊天对话
        async function sendChat() {
            const input = document.getElementById('chatInput').value.trim();
            if (!input) return alert('请输入问题');
            
            try {
                const result = await callApi('chat', { prompt: input });
                
                document.getElementById('chatOutput').textContent = result.response;
                if (result.thinking) {
                    document.getElementById('chatOutput').innerHTML += 
                        '\n\n<div class="thinking">思考过程: ' + result.thinking + '</div>';
                }
                document.getElementById('chatResult').style.display = 'block';
                
            } catch (error) {
                document.getElementById('chatOutput').innerHTML = 
                    '<div class="error">错误: ' + error.message + '</div>';
                document.getElementById('chatResult').style.display = 'block';
            }
        }
        
        // 文本生成
        async function generateText() {
            const prompt = document.getElementById('generatePrompt').value.trim();
            const maxTokens = parseInt(document.getElementById('maxTokens').value);
            const temperature = parseFloat(document.getElementById('temperature').value);
            
            if (!prompt) return alert('请输入提示词');
            
            try {
                const result = await callApi('generate', { 
                    prompt, 
                    max_tokens: maxTokens, 
                    temperature 
                });
                
                if (result.success) {
                    document.getElementById('generateOutput').textContent = result.result;
                    if (result.thinking) {
                        document.getElementById('generateOutput').innerHTML += 
                            '\n\n<div class="thinking">思考过程: ' + result.thinking + '</div>';
                    }
                    document.getElementById('generateResult').style.display = 'block';
                } else {
                    throw new Error(result.error);
                }
                
            } catch (error) {
                document.getElementById('generateOutput').innerHTML = 
                    '<div class="error">错误: ' + error.message + '</div>';
                document.getElementById('generateResult').style.display = 'block';
            }
        }
        
        // 文案润色
        async function rewriteText() {
            const text = document.getElementById('rewriteText').value.trim();
            const style = document.getElementById('rewriteStyle').value;
            
            if (!text) return alert('请输入需要润色的文本');
            
            try {
                const result = await callApi('rewrite', { text, style });
                
                if (result.success) {
                    document.getElementById('originalText').textContent = result.original;
                    document.getElementById('rewrittenText').textContent = result.rewritten;
                    if (result.thinking) {
                        document.getElementById('rewrittenText').innerHTML += 
                            '\n\n<div class="thinking">思考过程: ' + result.thinking + '</div>';
                    }
                    document.getElementById('rewriteResult').style.display = 'block';
                } else {
                    throw new Error(result.error);
                }
                
            } catch (error) {
                document.getElementById('rewrittenText').innerHTML = 
                    '<div class="error">错误: ' + error.message + '</div>';
                document.getElementById('rewriteResult').style.display = 'block';
            }
        }


        

        
        // 刷新状态
        async function refreshStatus() {
            try {
                const response = await fetch('/api/status');
                const data = await response.json();
                
                // 安全检查所有DOM元素是否存在
                const statusDot = document.getElementById('statusDot');
                const statusText = document.getElementById('statusText');
                
                if (statusDot && statusText) {
                    if (data.status === 'running') {
                        statusDot.classList.remove('offline');
                        statusText.textContent = '运行中';
                    } else {
                        statusDot.classList.add('offline');
                        statusText.textContent = '离线';
                    }
                }
                
                // 更新统计数字（安全检查）
                const generateCount = document.getElementById('generateCount');
                const rewriteCount = document.getElementById('rewriteCount');
                const chatCount = document.getElementById('chatCount');
                
                if (generateCount) generateCount.textContent = data.api_stats.generate.count;
                if (rewriteCount) rewriteCount.textContent = data.api_stats.rewrite.count;
                if (chatCount) chatCount.textContent = data.api_stats.chat.count;
                
                // 更新最近使用时间（安全检查）
                const generateTime = document.getElementById('generateTime');
                const rewriteTime = document.getElementById('rewriteTime');
                const chatTime = document.getElementById('chatTime');
                
                if (generateTime) generateTime.textContent = 
                    data.api_stats.generate.last_used ? new Date(data.api_stats.generate.last_used).toLocaleString('zh-CN') : '从未使用';
                if (rewriteTime) rewriteTime.textContent = 
                    data.api_stats.rewrite.last_used ? new Date(data.api_stats.rewrite.last_used).toLocaleString('zh-CN') : '从未使用';
                if (chatTime) chatTime.textContent = 
                    data.api_stats.chat.last_used ? new Date(data.api_stats.chat.last_used).toLocaleString('zh-CN') : '从未使用';
                
            } catch (error) {
                const statusDot = document.getElementById('statusDot');
                const statusText = document.getElementById('statusText');
                if (statusDot && statusText) {
                    statusDot.classList.add('offline');
                    statusText.textContent = '连接失败';
                }
            }
        }
        
        // 初始化状态
        refreshStatus();
        
        // 回车发送支持
        document.getElementById('chatInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendChat();
            }
        });
        
        document.getElementById('generatePrompt').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && e.ctrlKey) {
                e.preventDefault();
                generateText();
            }
        });
        
        // 量化模型功能
        function showQuantizePanel() {
            const panel = document.getElementById('quantizePanel');
            if (panel) {
                panel.style.display = 'block';
                return;
            }
            
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.id = 'quantizePanel';
            modal.style.display = 'block';
            modal.innerHTML = `
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>模型量化工具</h3>
                        <span class="close" onclick="closeQuantizePanel()">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>量化位数：</label>
                            <select id="quantizeBits" class="select-control">
                                <option value="4">4位量化 (推荐)</option>
                                <option value="8">8位量化</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>量化组大小：</label>
                            <input type="number" id="groupSize" class="form-control" value="128" min="32" max="256">
                        </div>
                        <div class="form-group">
                            <label>校准样本数：</label>
                            <input type="number" id="calibrationSamples" class="form-control" value="128" min="32" max="512">
                        </div>
                        <div class="progress-container" id="quantizeProgress" style="display: none;">
                            <div class="progress-bar">
                                <div class="progress-fill" id="progressFill"></div>
                            </div>
                            <div class="progress-text" id="progressText">0%</div>
                        </div>
                        <div id="quantizeResult" style="display: none; margin-top: 15px;"></div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-secondary" onclick="closeQuantizePanel()">取消</button>
                        <button class="btn" onclick="startQuantization()" id="quantizeBtn">开始量化</button>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }
        
        function closeQuantizePanel() {
            const panel = document.getElementById('quantizePanel');
            if (panel) {
                panel.style.display = 'none';
            }
        }
        
        async function startQuantization() {
            const bits = parseInt(document.getElementById('quantizeBits').value);
            const groupSize = parseInt(document.getElementById('groupSize').value);
            const samples = parseInt(document.getElementById('calibrationSamples').value);
            
            const btn = document.getElementById('quantizeBtn');
            const progress = document.getElementById('quantizeProgress');
            const result = document.getElementById('quantizeResult');
            
            btn.disabled = true;
            progress.style.display = 'block';
            result.style.display = 'none';
            
            try {
                const response = await fetch('/api/quantize', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ bits, group_size: groupSize, samples })
                });
                
                if (!response.ok) {
                    throw new Error('量化请求失败');
                }
                
                const data = await response.json();
                
                if (data.success) {
                    result.innerHTML = `<div class="success">量化成功！模型已重新加载。</div>`;
                    result.style.display = 'block';
                    
                    // 更新模型状态
                    setTimeout(() => {
                        refreshStatus();
                        closeQuantizePanel();
                    }, 2000);
                } else {
                    throw new Error(data.error || '量化失败');
                }
                
            } catch (error) {
                result.innerHTML = `<div class="error">错误: ${error.message}</div>`;
                result.style.display = 'block';
            } finally {
                btn.disabled = false;
            }
        }
        
        console.log('AI智能写作助手已加载');
        console.log('可用端点: /api/generate, /api/rewrite, /chat');
        console.log('新增功能: AQW模型量化支持');
    </script>
</body>
</html>